#include "public.h"
#include "IIC.h"

void IIC_start()
{
	IIC_SCL = 1;
	IIC_SDA = 1;
	delay_10us(1);
	IIC_SDA = 0;
	delay_10us(1);
	IIC_SCL = 0;
}
void IIC_stop()
{
	IIC_SCL = 1;
	IIC_SDA = 0;
	delay_10us(1);
	IIC_SDA = 1;
	delay_10us(1);
}
void IIC_ack()
{
	IIC_SCL = 0;
	IIC_SDA = 0;	  //answer
	delay_10us(1);
	IIC_SCL = 1;	
	delay_10us(1);
	IIC_SCL = 0;	
}
void IIC_no_ack()
{
	IIC_SCL = 0;
	IIC_SDA = 1;	 //not answer
	delay_10us(1);
	IIC_SCL = 1;	
	delay_10us(1);
	IIC_SCL = 0;	
}
unsigned char IIC_wait_ack()
{
	unsigned char time_temp = 0;
    IIC_SCL=1;
    delay_10us(1);
    while(IIC_SDA)
   {
   		time_temp++;
		if(time_temp>100)
		{
		 	IIC_stop();
			return 1;
		}
   }
   IIC_SCL=1;
   return 0; 
}

void IIC_write_byte(unsigned char dat)
{
	int i = 0;
	IIC_SCL = 0;	
	for(i=0;i<8;i++)
	{
		if(dat & 0x80)
			IIC_SDA=1;
		else
			IIC_SDA=0;
		dat <<= 1;
        IIC_SCL = 1;
	    delay_10us(1);	
		IIC_SCL = 0;
	    delay_10us(1);	

	}
}
unsigned char IIC_read_byte(unsigned char ack)
{
	int i = 0;
	unsigned char receive = 0;
	for(i=0;i<8;i++)
	{
		IIC_SCL = 0;
	    delay_10us(1);
		IIC_SCL = 1;
	    delay_10us(1);
		receive<<=1;
		if(IIC_SDA)receive++;	
	}
	if(!ack) 
		IIC_no_ack();
	else 
		IIC_ack();
	return receive;
}
